<template>
  <div>
    <!--首页开始-->
    <home v-if="currIndex==0"></home>
    <!--首页结束-->
    <!--投诉开始-->
    <complain v-if="currIndex==1"></complain>
    <!--投诉结束-->
    <!--设置开始-->
    <seting v-if="currIndex==2"></seting>
    <!--设置结束-->
    <!--tabbar开始-->
    <van-tabbar v-model="active" active-color="#07c160" inactive-color="#000">
      <van-tabbar-item
        v-for="(item,index) in tabbarList"
        :key="index"
        @click="Changetab(index,item.name)"
      >
        <span :class="currIndex == index ? active:''">{{item.text}}</span>
        <template slot="icon" slot-scope="props">
          <img :src="props.active ? item.active : item.normal" />
        </template>
      </van-tabbar-item>
    </van-tabbar>
    <!--tabbar结束-->
  </div>
</template>
<script>
var myMedia = null;
import home from "./home";
import complain from "./complain";
import seting from "./seting";
import { mapState } from "vuex";
export default {
  components: { home, complain, seting },
  data() {
    return {
      currIndex: 0,
      active: 0,
      tabbarList: [
        {
          name: "home",
          text: "首页",
          normal: require("../../../static/image/home_zy_h.png"),
          active: require("../../../static/image/home_zy.png")
        },
        {
          name: "count",
          text: "投诉与建议",
          normal: require("../../../static/image/home_ts_h.png"),
          active: require("../../../static/image/home_ts.png")
        },
        {
          name: "apply",
          text: "我的",
          normal: require("../../../static/image/alet_person_hui.png"),
          active: require("../../../static/image/alet_person.png")
        }
      ],
      exitAppTicker: 0,
      websocketinter: "",
      callmsg: [],
      audio: true
    };
  },
  computed: {
    ...mapState({
      token: state => state.Authorization,
      role_id: state => state.userData.role_id,
      id: state => state.userData.id,
      name: state => state.userData.name,
      project_company_id: state => state.userData.project_company_id,
      project_id: state => state.userData.project_company_id
    })
  },
  mounted() {
    // this.backbutton();
    if (localStorage.getItem("home-tab")) {
      var current = localStorage.getItem("home-tab");
      this.active = parseInt(current);
      this.currIndex = parseInt(current);
    }
    //管理员实时位置
    if (this.role_id == 3) {
      var that = this;
      if (that.global.managerWs && that.global.managerWs.readyState == 1) {
        //console.log("管理员已存在");
        that.sendws();
      } else {
        //console.log("管理员不存在");
        that.perwebsocket();
      }
    }
    //实时对讲
    if (this.token) {
      if (this.global.ws && this.global.ws.readyState == 1) {
        // //console.log("实时对讲socket已存在");
        this.onmessage();
      } else {
        // //console.log("实时对讲socket不存在");
        this.localSocket();
      }
    }
  },
  destroyed() {
    var that = this;
    document.removeEventListener("backbutton", that.exitApp, false);
    document.removeEventListener("backbutton", that.eventBackButton, false);
  },
  created() {
    var that = this;
    document.addEventListener("deviceready", that.onDeviceReady, false);
  },
  methods: {
    /**把实时对讲的websocket和manager的socnket都放首页了 */
    /*实时对讲*/
    onmessage() {
      let that = this;
      that.global.ws.onmessage = function(res) {
        ////console.log("收到实时对讲服务器内容", res);
        var data = res.data;
        if (typeof data == "string") {
          data = JSON.parse(data);
        }
        if (data.path) {
          that.callmsg.push(data.path);
          ////console.log("音频数组", that.callmsg);
          ////console.log("音频", data.path);
          //排队播放
          if (that.audio) {
            //如果没人
            that.audio = false; //改为有人排队了
            that.playv(that.callmsg[0]);
          }
        }
      };
    },
    //app.vue
    localSocket() {
      let that = this;
      if ("WebSocket" in window) {
        ////console.log("您的浏览器支持 WebSocket!");
        var serviceIp = "222.88.248.111:9666";
        that.ws = new WebSocket("ws://" + serviceIp + "?token=" + that.token);
        that.global.setWs(that.ws);
        that.interval = window.setInterval(function() {
          //每隔30秒钟发送一次心跳，避免websocket连接因超时而自动断开
          if (that.ws != null) {
            that.global.ws.send('{"type":"pong"}');
          }
        }, 179000);
        that.global.ws.onopen = function(res) {
          ////console.log(res);
          ////console.log("实时对讲连接已成功...");
        };
        that.onmessage();
        that.global.ws.onclose = function() {
          // 关闭 websocket
          ////console.log("实时对讲连接已关闭...");
          if (that.token) {
            setTimeout(() => {
              that.localSocket();
            }, 2000);
          }
        };
        that.global.ws.onerror = function() {
          ////console.log("实时对讲WebSocket连接发生错误");
        };
      } else {
        // 浏览器不支持 WebSocket
        ////console.log("您的浏览器不支持 WebSocket!");
      }
    },
    //播放
    playv(url) {
      var that = this;
      if (that.callmsg.length > 0) {
        // Play the audio file at url
        ////console.log("录音内容", url);
        myMedia = new Media(
          url,
          // success callback
          function() {
            // //console.log("playAudio():Audio Success");
          },
          // error callback
          function(err) {
            ////console.log(err);
            ////console.log("playAudio():Audio Error: " + err);
          },
          function(status) {
            ////console.log("状态值", status);
            if (status == 4) {
              ////console.log("播放完成");
              that.callmsg.splice(0, 1); //队列的第一个播放完毕，所以删除
              that.playv(that.callmsg[0]); //进行下一个请求并播放
            }
          }
        );
        // Play audio
        ////console.log("对象2", myMedia);
        myMedia.play();
      } else {
        //this.audio是一个data数据,用来记录是否有人排队
        that.audio = true; //如果队列没人排队，就告诉外面已经读完啦
      }
    },
    Changetab(index, val) {
      this.currIndex = index;
      localStorage.setItem("home-tab", this.currIndex);
    },
    sendws() {
      let _this = this;
      _this.websocketinter = window.setInterval(function() {
        //获取实时位置
        navigator.geolocation.getCurrentPosition(
          function(position) {
            var currentLat = position.coords.latitude;
            var currentLng = position.coords.longitude;
            //console.log("经度", currentLat, "纬度", currentLat);
            var data = {
              user_id: _this.id,
              name: _this.name,
              project_id: _this.project_id,
              project_company_id: _this.project_company_id,
              latitude: currentLat,
              longitude: currentLng
            };
            var msg = {
              type: "SystemLocation",
              msg: data
            };
            msg = JSON.stringify(msg);
            if (_this.global.managerWs.readyState == 1) {
              _this.global.managerWs.send(msg);
              //console.log("管理员数据发送中...", msg);
            }
          },
          function(error) {
            //console.log(error.message, "温馨提示");
          }
        );
      }, 20000);
    },
    /*实时管理员位置*/

    perwebsocket() {
      var serviceIp = "222.88.248.111:5898";
      let that = this;
      that.ws = new WebSocket("ws://" + serviceIp + "?token=" + that.token);
      that.global.managerWssetWs(that.ws);
      this.interval = window.setInterval(function() {
        //每隔30秒钟发送一次心跳，避免websocket连接因超时而自动断开
        if (that.ws != null) {
          that.ws.send('{"type":"pong"}');
        }
      }, 179000);
      that.global.managerWs.onopen = () => {
        let _this = this;
        //console.log("实时管理员位置socket连接成功");
        // Web Socket 已连接上，使用 send() 方法发送数据
        _this.sendws();
      };
      that.global.managerWs.onmessage = event => {
        //console.log("实时管理员位置socket数据接收中...", event);
      };
      that.global.managerWs.onerror = function() {
        //console.log("实时管理员位置socket连接发生错误");
      };
      that.global.managerWs.onclose = function() {
        let that = this;
        if (that.token) {
          setTimeout(() => {
            that.perwebsocket();
          }, 3000);
        }
        // 关闭 websocket
        //console.log("实时管理员位置socket连接已关闭...");
      };

      // 路由跳转时结束websocket链接
      // 路由跳转时结束websocket链接
      // this.$router.afterEach(function() {
      //   ws.send('{"type":"Maintenance"}');
      //   window.clearInterval(that.interval);
      // });
    },

    //当前页面router
    //设备API可以使用了,然后在vue的methods中添加如下方法
    onDeviceReady() {
      //console.log("监听");
      var that = this;
      document.addEventListener("backbutton", that.eventBackButton, false);
    }, //监听返回键按钮事件
    eventBackButton() {
      var that = this;
      that.$toast({ message: "再点一次退出" });
      //这里使用的是vantUI框架的弹窗提示，此处可根据自身项目进行更改
      document.removeEventListener("backbutton", that.eventBackButton, false); //注销返回键
      document.addEventListener("backbutton", that.exitApp, false); //绑定退出事件
      var intervalID = setInterval(() => {
        document.clearInterval(intervalID);
        document.removeEventListener("backbutton", that.exitApp, false);
        document.addEventListener("backbutton", that.eventBackButton, false);
      }, 2000);
    }, // 关闭app
    exitApp() {
      var that = this;
      navigator.app.exitApp();
    }
  }
};
</script>
<style lang="less" scoped>
.active_tab img {
  width: 26px;
  height: 26px;
}
</style>